<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    width="1100px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '94px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('device.deviceSerialNumber')" prop="sn">
            <TextInput
              v-model="formData.sn"
              :label="$t('device.deviceSerialNumber')"
              verify-type="alnum"
              :disabled="type === 'edit'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('device.deviceName')"
            prop="name"
            :label-width="language === 'en' ? '180px' : '80px'"
          >
            <TextInput
              v-model="formData.name"
              :label="$t('device.deviceName')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('device.deviceModel')" prop="model">
            <TextInput
              v-model="formData.model"
              :label="$t('device.deviceModel')"
              verify-type="alnuml"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="设备类型"
            prop="type"
            :label-width="language === 'en' ? '180px' : '80px'"
          >
            <BaseSelect
              v-model="formData.type"
              :options="g_options.deviceTypeOptions"
              :label="$t('device.deviceCategory')"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="所在组" prop="group">
            <BaseSelect
              v-model="formData.group"
              :options="g_options.deviceTypeOptions"
              label="所在组"
            />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item :label="$t('device.hoodSerialNumber')" prop="bind">
            <TextInput
              v-model="formData.bind"
              :label="$t('device.hoodSerialNumber')"
              verify-type="int"
            />
          </el-form-item>
        </el-col> -->
        <!-- <el-col v-if="type === 'edit'" :span="12">
          <el-form-item :label="$t('device.deviceStatus')" prop="status">
            <BaseSelect
              v-model="formData.status"
              :options="g_options.deviceStatusOptions"
              :label="$t('device.deviceStatus')"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item :label="$t('device.deviceAddress')" prop="address">
            <TextInput
              v-model="formData.address"
              :placeholder="
                g_rules.zhAndEnShowMsg(
                  $t('public.pleaseSelect'),
                  $t('device.deviceAddress')
                )
              "
              readonly
              @click="handleMapSelect"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24">
          <el-form-item :label="$t('public.remark')" prop="note">
            <TextInput
              v-model="formData.note"
              type="textarea"
              :rows="2"
              maxlength="256"
              :label="$t('public.remark')"
            />
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <!-- <el-alert title="特别说明：" type="warning" show-icon :closable="false">
      带星号（<span style="color: red">*</span
      >）的信息请认真核对后在修改，避免错误导致设备使用异常！
    </el-alert> -->
    <template #footer>
      <div class="form-dialog-footer" style="padding-top: 10px">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
    <SearchMap
      v-if="searchMapVisible"
      v-model="searchMapVisible"
      :regionName="regionName"
      @add="handleAddRegion"
    />
  </BaseDialog>
</template>

<script setup>
const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  sn: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() =>
  props.type === 'add' ? g_t('device.addDevice') : g_t('device.editDevice')
)

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  sn: '',
  name: '',
  // bind: '',
  model: '',
  type: '',
  // group: '',
  // status: '',
  address: '',
  location: ''
  // note: ''
})
const rules = {
  sn: g_rules.commonInputText(g_t('device.deviceSerialNumber')),
  name: g_rules.commonInputText(g_t('device.deviceName')),
  // bind: g_rules.commonInputText(g_t('device.hoodSerialNumber')),
  model: g_rules.commonInputText(g_t('device.deviceModel')),
  type: g_rules.selectRule(g_t('device.deviceCategory')),
  // group: g_rules.selectRule('所在组'),
  // status: g_rules.selectRule(g_t('device.deviceStatus')),
  address: g_rules.selectRule(g_t('device.deviceAddress'))
}
const searchMapVisible = ref(false)
const regionName = ref('')

onMounted(() => {
  props.type === 'edit' && getFormData()
})

const getFormData = _ => {
  g_api.device.apiDeviceQueryDetail({ sn: props.sn }).then(({ code, data }) => {
    if (code === '200' && data) {
      formData.value = {
        ...formData.value,
        appId: '',
        tenantId: '',
        status: ''
      }
      g_utils.assignFormData(formData.value, data)
      console.log('formData.value', formData.value)
    }
  })
}

const handleClose = _ => {
  dialogVisible.value = false
}

const handleMapSelect = _ => {
  searchMapVisible.value = true
  regionName.value = formData.value.address
}

const handleAddRegion = (type, data) => {
  // console.log('handleAddRegion', type, data)
  const { formattedAddress, lnglat } = data
  formData.value.address = formattedAddress
  formData.value.location = lnglat.join(',')
  // formData.value.location = {
  //   lng: lnglat[0],
  //   lat: lnglat[1]
  // }
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    const urlMethod =
      props.type === 'add'
        ? g_api.device.apiDeviceCreate
        : g_api.device.apiDeviceUpdate
    urlMethod(formData.value)
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss"></style>
